package com.wavercaz.freeforum.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wavercaz.freeforum.pojo.CommonSearchParam;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;

// 查询工具，用于返回mybatisPlus需要的QueryWrapper对象
    public class QueryUtil {

    public static QueryWrapper getQueryWrapper(CommonSearchParam.Search[] searches) {
        QueryWrapper<Object> queryWrapper = new QueryWrapper<>();
        if(searches != null && searches.length != 0) {
            String key = null;
            for (CommonSearchParam.Search search : searches) {
                if(search.getValue() == null) continue;

                // 驼峰转下划线，比如：createDate -> create_date，为了与数据库的字段对应
                key = StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(search.getKey()), '_').toLowerCase();
                switch (search.getRule()) {
                    case "=":
                        queryWrapper.eq(key, search.getValue());
                        break;
                    case "like":
                        queryWrapper.like(key, search.getValue());
                        break;
                    case ">":
                        queryWrapper.gt(key, search.getValue());
                        break;
                    case ">=":
                        queryWrapper.ge(key, search.getValue());
                        break;
                    case "<":
                        queryWrapper.lt(key, search.getValue());
                        break;
                    case "<=":
                        queryWrapper.le(key, search.getValue());
                        break;
                    case "scope":
                        ArrayList values = (ArrayList) search.getValue();
                        queryWrapper.between(key,values.get(0),values.get(1));
                        break;
                }
            }
        }
        return queryWrapper;
    }
}
